package com.work.bookstore.controller;


import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.work.bookstore.mapper.BookMapper;
import com.work.bookstore.pojo.Book;


import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ppg007
 * @date 2021/1/1 13:46
 */
@Controller
public class BookController {

    @Autowired
    private BookMapper bookMapper;

    @RequestMapping(value = "/getBookByCategory",method = RequestMethod.POST)
    @ResponseBody
    public String getBookByCategory(HttpServletRequest request){
        JSONArray jsonArray=new JSONArray();
        String cateGory=request.getParameter("category");
        List<Book> bookList=bookMapper.queryBookByCategory(cateGory);
        for (Book  book:bookList){
            jsonArray.put(putData(book));
        }
        return jsonArray.toString();
    }

    @RequestMapping(value = "/getBookByName",method = RequestMethod.POST)
    @ResponseBody
    public String getBookByName(HttpServletRequest request){
        String bookName=request.getParameter("bookName");
        List<Book> bookList= bookMapper.queryBookByName(bookName);
        JSONArray jsonArray=new JSONArray();
        for (Book book:bookList){
            jsonArray.put(putData(book));
        }

        return jsonArray.toString();
    }

    @RequestMapping(value = "/getBookById",method = RequestMethod.POST)
    @ResponseBody
    public String getBookById(HttpServletRequest request){
        String bookList=request.getParameter("bookList");
        String[] temp=bookList.split("∫");
        JSONArray jsonArray=new JSONArray();
        for (String t: temp){
            jsonArray.put(putData(bookMapper.queryBookByOrder(Integer.parseInt(t))));
        }
        return jsonArray.toString();
    }

    public static JSONObject  putData(Book book){
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("bookName",book.getBookName());
        jsonObject.put("bookPrice",book.getBookPrice());
        jsonObject.put("bookRest",book.getBookRest());
        jsonObject.put("bookTitle",book.getBookTitle());
        jsonObject.put("bookImage",book.getBookImage());
        jsonObject.put("bookDescribe",book.getBookDescribe());
        jsonObject.put("bookPress",book.getBookPress());
        jsonObject.put("pressDate",book.getPressDate());
        jsonObject.put("bookAuthor",book.getBookAuthor());
        jsonObject.put("bookCategory",book.getBookCategory());
        jsonObject.put("bookId",book.getId());
        return jsonObject;
    }
}
